package com.xy_pro.xymanager.controller;

import com.xy_pro.xymanager.auth.dto.LoginRequest;
import com.xy_pro.xymanager.auth.dto.ResultResponse;
import com.xy_pro.xymanager.dto.ScoreTitleDTO;
import com.xy_pro.xymanager.dto.SearchScoreRequest;
import com.xy_pro.xymanager.entity.ScoreData;
import com.xy_pro.xymanager.entity.UserEntity;
import com.xy_pro.xymanager.payload.ErrorResponse;
import com.xy_pro.xymanager.payload.UploadResponse;
import com.xy_pro.xymanager.repository.ScoreDataRepository;
import com.xy_pro.xymanager.repository.UserRepository;
import com.xy_pro.xymanager.service.ScoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.PagedModel;
import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/score")
public class ScoreController {

    @Autowired
    private ScoreService scoreService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ScoreDataRepository scoreDataRepository;

    Logger logger = LoggerFactory.getLogger(ScoreController.class);

    @GetMapping("/list")
    public ResultResponse<PagedModel<EntityModel<ScoreTitleDTO>>> scoreList(@RequestParam(required = false) String title,
                                                                            @RequestParam(defaultValue = "1") Integer currentPage,
                                                                            @RequestParam(defaultValue = "10") int pageSize,
                                                                            PagedResourcesAssembler<ScoreTitleDTO> pagedResourcesAssembler){
        logger.info("获取月考成绩列表：title = {}, pageNo = {}, pageSize = {}", title, currentPage, pageSize);
        Page<ScoreTitleDTO> stringList = scoreService.getScoreList(title, currentPage, pageSize);
        PagedModel<EntityModel<ScoreTitleDTO>> pagedModel = pagedResourcesAssembler.toModel(stringList);
        return ResultResponse.success(pagedModel);
    }

    @PostMapping("/userscore")
    public ResultResponse<ScoreData> queryUserScore(@RequestBody LoginRequest userEntity){
        System.out.println("===== 进入 Controller 方法 ====="); // 强制打
        logger.info("<UNK> userEntity = ");
        logger.info("queryUserScore: {}", userEntity.getUsername());
        String userName = userEntity.getUsername();
        if (userName == null || userName.isEmpty()){
//            ErrorResponse error = new ErrorResponse("学生姓名不能为空");
            return ResultResponse.error(HttpStatus.BAD_REQUEST.value(), "学生姓名不能为空");
//            return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
        }
        ScoreData scoreData = scoreService.getUserScoreData(userName);
        if(scoreData == null){
//            ErrorResponse error = new ErrorResponse("当前学生没有成绩展示，请联系管理员");
            return ResultResponse.error(HttpStatus.BAD_REQUEST.value(), "当前学生没有成绩展示，请联系管理员");
        } else {
            return ResultResponse.success(scoreData);
        }
    }

    @PostMapping("/status")
    public ResultResponse<Integer> changeScoreStatus(@RequestBody ScoreTitleDTO dto){
        String title = dto.getTitle();
        boolean isVisible = dto.isVisible();
        logger.info("<更新月考成绩可见性：>title = {}, isVisible = {}", title, isVisible);
        int count = scoreDataRepository.updateIsVisibleByTitle(title, isVisible);
        return ResultResponse.success(count);
    }

    @PostMapping("/search")
    public ResultResponse<?> searchScore(@RequestBody SearchScoreRequest searchRequest) {
        String title = searchRequest.title;
        String studentName = searchRequest.studentName;
        if (title.isEmpty()){
            ErrorResponse error = new ErrorResponse("标题不能为空");
            return ResultResponse.error(HttpStatus.BAD_REQUEST.value(), "标题不能为空");
//            return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
        }
        if (studentName == null || studentName.isEmpty()){
            ErrorResponse error = new ErrorResponse("学生姓名不能为空");
            return ResultResponse.error(HttpStatus.BAD_REQUEST.value(), "学生姓名不能为空");
//            return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
        }
        Optional<UserEntity> studentOptional = userRepository.findByName(studentName);
        if (studentOptional.isPresent()) {/// /学生存在
            System.out.println("tile:" + title + ", studentName:" + studentName);
            Optional<ScoreData> data = scoreDataRepository.findScoreDataByNameAndTitle(studentName, title);
            if (data.isPresent()) {
                return ResultResponse.success(data.get().getData());
//                return new ResponseEntity<>(data.get().getData(), HttpStatus.OK);
            } else  {
                ErrorResponse error = new ErrorResponse("学生成绩不存在");
                return ResultResponse.error(HttpStatus.BAD_REQUEST.value(), "学生成绩不存在");
//                return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
            }
        }

        return ResultResponse.error(HttpStatus.BAD_REQUEST.value(), "学生成绩不存在");

    }


    @PostMapping("/upload")
    public ResultResponse<?> uploadFile(@RequestParam("title") String title, @RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        System.out.println("title: " + title);
        if (file.isEmpty()) {
            return ResultResponse.error(HttpStatus.BAD_REQUEST.value(), "请选择要上传的文件");
        }
        if(title.isEmpty()){
            return ResultResponse.error(HttpStatus.BAD_REQUEST.value(), "标题不能为空！");
        }

        // 检查文件格式
        if (!file.getOriginalFilename().endsWith(".xlsx")) {
            return ResultResponse.error(HttpStatus.BAD_REQUEST.value(), "请上传.xlsx格式的Excel文件");
        }

        try {
            // 处理Excel文件
            UploadResponse response = scoreService.processExcel(title, file);

            // 如果有错误，返回部分成功状态
            if (response.getFailedRows() > 0) {
                return ResultResponse.error(HttpStatus.PARTIAL_CONTENT.value(), "部分成功");
//                return new ResponseEntity<>(response, HttpStatus.PARTIAL_CONTENT);
            }

            logger.info("上传月考成绩成功 {}", response);
            // 全部成功
//            return new ResponseEntity<>(response, HttpStatus.OK);
            return ResultResponse.success(response);

        } catch (Exception e) {
            ErrorResponse error = new ErrorResponse("上传文件失败: " + e.getMessage());
//            return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
            return ResultResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "上传文件失败：" + e.getMessage());
        }
    }
}
